package com.magiccompass.alipay.barcode.controller;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.support.PagedListHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.magiccompass.alipay.barcode.entity.MerchantTransaction;
import com.magiccompass.alipay.barcode.model.MerchantTransactionQuerySummaryModel;
import com.magiccompass.alipay.barcode.pageform.MerchantTransactionListPageForm;
import com.magiccompass.alipay.barcode.pageform.TransactionQueryPageForm;
import com.magiccompass.alipay.barcode.security.model.LoginUserModel;
import com.magiccompass.alipay.barcode.service.MerchantBusinessService;
import com.magiccompass.alipay.barcode.util.DateTimeUtil;
import com.magiccompass.alipay.barcode.util.MerchantTransactionUtil;
import com.magiccompass.alipay.barcode.util.UserUtil;

@Controller
@RequestMapping(value="/merchant")
public class MerchantSiteController {
	static Logger logger = LogManager.getLogger(MerchantSiteController.class.getName());
	
	@Resource(name="merchantBusinessService")
	private MerchantBusinessService merchantBusinessService;
	
	@RequestMapping(method = RequestMethod.GET)
    public ModelAndView home() {
        ModelAndView model = new ModelAndView("merchant/home");
        return model;
    }
	
	@RequestMapping(value="/inputTransaction", method = {RequestMethod.GET,RequestMethod.POST})
    public String inputTransaction(Model model) {
		LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
		//logger.info(currentUser.getUsername());
		model.addAttribute("merchantName", currentUser.getDbUserInfo().getMerchant().getMerchantName());
		return "merchant/inputTransaction";
    }
	
	@RequestMapping(value="/scanTransaction", method = {RequestMethod.GET,RequestMethod.POST})
    public String scanTransaction(Model model,HttpServletRequest request) {
		LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
		//logger.info(currentUser.getUsername());
		model.addAttribute("merchantName", currentUser.getDbUserInfo().getMerchant().getMerchantName());
		model.addAttribute("scannedBarcode", request.getParameter("barcode"));
		return "merchant/scanTransaction";
    }
	
	@RequestMapping(value="/paymentConfirm", method = {RequestMethod.GET,RequestMethod.POST})
    public String paymentConfirm(Model model,HttpServletRequest request) {
		String totalAmt = request.getParameter("totalAmt");
		String barcode = request.getParameter("barcode");
		LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
		MerchantTransaction mt = null;
		mt = MerchantTransactionUtil.makeBasicMerchantTransaction(merchantBusinessService.findMerchantById(currentUser.getDbUserInfo().getMerchant().getId()), new BigDecimal(totalAmt), merchantBusinessService);

		model.addAttribute("merchantTransactionId", mt.getId());
		model.addAttribute("totalAmt", mt.getTotalAmount());
		model.addAttribute("merchantName", mt.getMerchant().getMerchantName());
		model.addAttribute("barcode", barcode);
        return "merchant/paymentConfirm";
    }
	
	@RequestMapping(value="/transactionQuery", method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView transactionQuery(@ModelAttribute("queryPageForm") TransactionQueryPageForm tqpf,Model model,HttpServletRequest request) {
		String submitType = request.getParameter("submitType");
		String paging = request.getParameter("paging");
		PagedListHolder<MerchantTransactionListPageForm> plh = null;
		LoginUserModel currentUser = UserUtil.getCurrentLoginUser();
		Integer merchantId = currentUser.getDbUserInfo().getMerchant().getId();
		Integer userRoleId = currentUser.getDbUserInfo().getRoleId();
		if("q".equals(submitType)){ // user click query button
			String fromDate = tqpf.getFromDate();
			String toDate = tqpf.getToDate();
			
			Timestamp fromTimestamp = DateTimeUtil.getTimestampFromStringByFormat(fromDate, "yyyy-MM-dd");
			Timestamp toTimestamp = DateTimeUtil.getTimestampFromStringByFormat(toDate, "yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(toTimestamp.getTime());
			calendar.setTimeInMillis(calendar.getTimeInMillis());
			calendar.add(Calendar.DATE, 1); // because toDate return only yyyy-mm-dd, we need add one more day to include toDate.
			
			long fromTimestampMS = fromTimestamp.getTime();
			long toTimestampMS = calendar.getTimeInMillis();
			
			List<MerchantTransaction> dbMTList = merchantBusinessService.getMerchantTransactionListWithAlipayStatusOnlyByUpdateTime(fromTimestampMS, toTimestampMS, merchantId);
			
			MerchantTransactionQuerySummaryModel mtqsm = new MerchantTransactionQuerySummaryModel();
			
			if(dbMTList != null && dbMTList.size()>0){
				List<MerchantTransactionListPageForm> pageList =  MerchantTransactionUtil.makeMerchantTransactionListPageForm(dbMTList);
				
				plh = new PagedListHolder<MerchantTransactionListPageForm>(pageList);
				plh.setPage(0);
				plh.setPageSize(10);
				request.getSession().setAttribute("pagedListHolder", plh);
				model.addAttribute("pagedList", plh.getPageList());
				
				int successCountNumber=0;
				int cancelCountNumber=0;
				int refundCountNumber=0;
				int failedCountNumber=0;
				String mtStatus;
				BigDecimal totalAmount = new BigDecimal(0);
				BigDecimal expenditureAmount = new BigDecimal(0);
				BigDecimal refundAmount = new BigDecimal(0);
				totalAmount.setScale(2,RoundingMode.HALF_UP);
				for(MerchantTransactionListPageForm mtlpf:pageList){
					mtStatus = mtlpf.getStatusCode();
					if("S".equals(mtStatus)){
						successCountNumber++;
						totalAmount = totalAmount.add(mtlpf.getTotalAmount());
						expenditureAmount = expenditureAmount.add(mtlpf.getTotalAmount());
					}else if("C".equals(mtStatus)){
						cancelCountNumber++;
					}else if("E".equals(mtStatus)){
						refundCountNumber++;
						totalAmount = totalAmount.subtract(mtlpf.getTotalAmount());
						refundAmount = refundAmount.add(mtlpf.getTotalAmount());
					}else{
						failedCountNumber++;
					}					
				}
				mtqsm.setCancelCountNumber(cancelCountNumber);
				mtqsm.setFailedCountNumber(failedCountNumber);
				mtqsm.setFromDate(fromDate);
				mtqsm.setRefundCountNumber(refundCountNumber);
				mtqsm.setSuccessCountNumber(successCountNumber);
				mtqsm.setToDate(toDate);
				mtqsm.setTotalAmount(totalAmount);
				mtqsm.setExpenditureAmount(expenditureAmount);
				mtqsm.setRefundAmount(refundAmount);
			}else{
				request.getSession().setAttribute("pagedListHolder", new PagedListHolder<MerchantTransactionListPageForm>());
			}
			request.getSession().setAttribute("querySummaryModel", mtqsm);
			model.addAttribute("querySummaryModel", mtqsm);
		}else if("t".equals(paging)){ // user click page
			String page = request.getParameter("page");
			plh = (PagedListHolder<MerchantTransactionListPageForm>)request.getSession().getAttribute("pagedListHolder");
			if ("next".equals(page)){
				plh.nextPage();
			}else if ("previous".equals(page)){
				plh.previousPage();
			}
			model.addAttribute("pagedList", plh.getPageList());
			MerchantTransactionQuerySummaryModel mtqsm = (MerchantTransactionQuerySummaryModel)request.getSession().getAttribute("querySummaryModel");
			model.addAttribute("querySummaryModel", mtqsm);
		}else{ // default
			
		}
		if(2 == userRoleId){
			model.addAttribute("userRole", "manager");
		}else if(2 == userRoleId){
			model.addAttribute("userRole", "cashier");
		}
		return new ModelAndView("merchant/transactionQueryList");
    }
}